<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>图书管理系统 - 用户端</title>
    <!-- 引入 Google Fonts 的艺术字体 -->
    <link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: '微软雅黑', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
            overflow: hidden;
            background-color: #f5f6fa;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 200px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar h2 {
            text-align: center;
            margin-bottom: 30px;
            /* 使用艺术字体 */
            font-family: 'Pacifico', cursive;
        }

        .sidebar ul {
            list-style-type: none;
            padding: 0;
        }

        .sidebar li {
            padding: 15px 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar li:hover {
            background-color: #34495e;
        }

        .sidebar li.active {
            background-color: #3498db;
        }

        /* 主内容区域样式 */
        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .header {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background-color: #3498db;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-weight: bold;
        }

        /* 选项卡内容样式 */
        .tab-content {
            display: none;
            animation: fadeIn 0.5s ease;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            min-height: 70vh;
        }

        .tab-content.active {
            display: block;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 搜索框样式 */
        .search-box {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .search-box input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .search-box button {
            background-color: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-box button:hover {
            background-color: #2980b9;
        }

        /* 数据表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th,
        .data-table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        .data-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }

        .data-table tr:hover {
            background-color: #f9f9f9;
        }

        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn-primary {
            background-color: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-secondary {
            background-color: #7f8c8d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #6c797d;
        }

        /* 借阅状态标签 */
        .status-tag {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-available {
            background-color: #2ecc71;
            color: white;
        }

        .status-unavailable {
            background-color: #e74c3c;
            color: white;
        }

        /* 分页样式 */
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 5px;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }

        .pagination button.active {
            background-color: #3498db;
            color: white;
            border-color: #3498db;
        }

        /* 用户信息卡片 */
        .user-card {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            margin: 0 auto;
        }

        .user-card h3 {
            margin-top: 0;
            text-align: center;
        }

        .user-card .info-item {
            margin-bottom: 15px;
        }

        .user-card .info-label {
            font-weight: bold;
            color: #7f8c8d;
        }

        .user-card .info-value {
            margin-top: 5px;
        }

        /* 首页图片样式 */
        #home img {
            width: 100%;
            height: auto;
            object-fit: cover;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 30%;
            border-radius: 8px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>

<body>
<!-- 侧边栏导航 -->
<div class="sidebar">
    <h2>图书管理系统</h2>
    <ul>
        <li class="active" data-tab="home"><i class="fa fa-home"></i> 首页</li>
        <li data-tab="search"><i class="fa fa-search"></i> 图书搜索</li>
        <li data-tab="borrowed"><i class="fa fa-book"></i> 我的借阅</li>
        <li data-tab="reservations"><i class="fa fa-calendar"></i> 我的预约</li>
        <li data-tab="profile"><i class="fa fa-user"></i> 个人信息</li>
    </ul>
</div>

<!-- 主内容区域 -->
<div class="main-content">
    <div class="header">
        <!-- 新增欢迎语容器，保持原有布局 -->
        <div class="welcome-message" id="welcomeMsg">欢迎回来，访客</div>
        <div class="user-info">
            <div class="user-avatar">张</div>
            <div>
                <div class="username" id="currentUsername">未登录</div>
                <div class="user-role">普通用户</div>
            </div>
        </div>
    </div>

    <!-- 首页 -->
    <div id="home" class="tab-content active">
        <!-- 添加图片 -->
        <img src="/usermain.jpg" alt="首页图片">
    </div>

    <!-- 图书搜索 -->
    <div id="search" class="tab-content">
        <h2>图书搜索</h2>

        <div class="search-box">
            <input type="text" id="title-search" placeholder="请输入书名">
            <input type="text" id="author-search" placeholder="请输入作者">
            <button onclick="performSearch(1)">搜索</button>
        </div>

        <table class="data-table">
            <thead>
            <tr>
                <th>书名</th>
                <th>类型</th>
                <th>作者</th>
                <th>出版社</th>
                <th>库存</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="search-results">
            <!-- 搜索结果将动态插入这里 -->
            </tbody>
        </table>

        <div class="pagination" id="pagination">
            <!-- 分页按钮将动态插入这里 -->
        </div>
    </div>

    <!-- 我的借阅 -->
    <div id="borrowed" class="tab-content">
        <h2>我的借阅</h2>

        <table class="data-table">
            <thead>
            <tr>
                <th>书名</th>
                <th>借阅日期</th>
                <th>应还日期</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="borrowed-results">
            <!-- 原始示例数据已删除，由 JS 动态填充 -->
            </tbody>
        </table>
    </div>

    <!-- 我的预约 -->
    <div id="reservations" class="tab-content">
        <h2>我的预约</h2>

        <table class="data-table">
            <thead>
            <tr>
                <th>书名</th>
                <th>预约时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="reservation-results">
            <!-- 预约记录将动态插入这里 -->
            </tbody>
        </table>
    </div>


    <!-- 个人信息 -->
    <div id="profile" class="tab-content">
        <h2>个人信息</h2>

        <div class="user-card">
            <h3>个人资料</h3>

            <div class="info-item">
                <div class="info-label">用户名</div>
                <div class="info-value" id="username"></div>
            </div>

            <div class="info-item">
                <div class="info-label">真实姓名</div>
                <div class="info-value" id="realName"></div>
            </div>

            <div class="info-item">
                <div class="info-label">联系方式</div>
                <div class="info-value" id="phone"></div>
            </div>

            <div class="info-item">
                <div class="info-label">注册日期</div>
                <div class="info-value" id="registerTime"></div>
            </div>

            <div class="info-item">
                <div class="info-label">罚款金额</div>
                <div class="info-value" id="fineAmount"></div>
            </div>

            <button class="btn btn-primary" onclick="openEditInfoModal()">修改信息</button>
            <button class="btn btn-secondary" onclick="openChangePasswordModal()">修改密码</button>
        </div>
    </div>
</div>

<!-- 修改信息模态框 -->
<div id="editInfoModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeEditInfoModal()">&times;</span>
        <h2>修改信息</h2>
        <input type="text" id="editUsername" placeholder="用户名">
        <input type="text" id="editRealName" placeholder="真实姓名">
        <input type="text" id="editPhone" placeholder="联系方式">
        <button class="btn btn-primary" onclick="saveEditInfo()">保存</button>
    </div>
</div>

<!-- 修改密码模态框 -->
<div id="changePasswordModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeChangePasswordModal()">&times;</span>
        <h2>修改密码</h2>
        <input type="password" id="oldPassword" placeholder="旧密码">
        <input type="password" id="newPassword" placeholder="新密码">
        <input type="password" id="confirmPassword" placeholder="确认新密码">
        <button class="btn btn-primary" onclick="saveChangePassword()">保存</button>
    </div>
</div>



<script>
    // 侧边栏导航切换（保持不变）
    document.querySelectorAll('.sidebar li').forEach(item => {
        item.addEventListener('click', function () {
            document.querySelectorAll('.sidebar li').forEach(li => {
                li.classList.remove('active');
            });
            this.classList.add('active');
            const tabId = this.getAttribute('data-tab');
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.getElementById(tabId).classList.add('active');
        });
    });

    // 快速操作按钮切换标签（保持不变）
    function switchTab(tabId) {
        document.querySelectorAll('.sidebar li').forEach(li => {
            li.classList.remove('active');
        });
        document.querySelector(`.sidebar li[data-tab="${tabId}"]`).classList.add('active');
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.getElementById(tabId).classList.add('active');
    }

    function performSearch(page) {
        const title = document.getElementById('title-search').value;
        const author = document.getElementById('author-search').value;
        searchBooks(page, title, author);
    }

    // 搜索图书功能
    async function searchBooks(page, title = '', author = '') {
        try {
            const response = await fetch(`/user/book?pageNum=${page}&pageSize=10&title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`, {
                method: 'GET'
            });

            const data = await response.json();

            if (data.code === 1) {
                const results = data.data.rows;
                const tableBody = document.getElementById('search-results');
                tableBody.innerHTML = '';

                results.forEach(book => {
                    // 根据库存判断是否可借
                    const availabilityText = book.stock > 0 ? '可借' : '不可借';
                    const statusClass = book.stock > 0 ? 'status-available' : 'status-unavailable';
                    const borrowButton = book.stock > 0 ?
                        `<button class="btn btn-primary" onclick="borrowBook('${book.id}')">借阅</button>` :
                        `<button class="btn btn-secondary" disabled>无库存</button>`;

                    const row = document.createElement('tr');
                    row.innerHTML = `
                    <td>${book.title}</td>
                    <td>${book.bookClassify}</td>
                    <td>${book.author}</td>
                    <td>${book.publisher}</td>
                    <td>${book.stock}</td>
                    <td><span class="status-tag ${statusClass}">${availabilityText}</span></td>
                    <td>
                        ${borrowButton}
                        <button class="btn btn-secondary" onclick="reserveBook('${book.id}')">预约</button>
                    </td>
                `;
                    tableBody.appendChild(row);
                });

                const total = data.data.total;
                const totalPages = Math.ceil(total / 10);
                const pagination = document.getElementById('pagination');
                pagination.innerHTML = '';

                for (let i = 1; i <= totalPages; i++) {
                    const button = document.createElement('button');
                    button.textContent = i;
                    if (i === page) {
                        button.classList.add('active');
                    }
                    button.addEventListener('click', () => performSearch(i));
                    pagination.appendChild(button);
                }

                const goToPageInput = document.createElement('input');
                goToPageInput.type = 'number';
                goToPageInput.min = 1;
                goToPageInput.max = totalPages;
                goToPageInput.placeholder = '前往页码';

                const goToPageButton = document.createElement('button');
                goToPageButton.textContent = '前往';
                goToPageButton.addEventListener('click', () => {
                    const pageNum = parseInt(goToPageInput.value);
                    if (!isNaN(pageNum) && pageNum >= 1 && pageNum <= totalPages) {
                        performSearch(pageNum);
                    }
                });

                pagination.appendChild(document.createTextNode(`共 ${totalPages} 页`));
                pagination.appendChild(goToPageInput);
                pagination.appendChild(goToPageButton);
            } else {
                alert(data.msg || '获取数据失败');
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }



    // 借阅图书
    async function borrowBook(bookId) {
        const username = document.getElementById('currentUsername').textContent;
        if (username === '未登录') {
            alert('请先登录');
            return;
        }

        try {
            const response = await fetch(`/user/borrow?bookId=${bookId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await response.json();
            if (data.code === 1) {
                alert('借阅成功！');
                searchBooks(1); // 刷新图书列表
                loadBorrowedBooks(); // 刷新借阅记录
            } else {
                alert(data.msg || '借阅失败');
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }



    // 预约图书
    // 修改 reserveBook 函数
    async function reserveBook(bookId) {
        if (confirm('确定要预约这本书吗？')) {
            try {
                const response = await fetch('/user/reservation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        bookId: bookId
                    })
                });
                const data = await response.json();
                if (data.code === 1) {
                    alert('预约成功！');
                    searchBooks(1); // 刷新搜索结果
                    loadReservations(); // ✅ 新增：刷新预约记录
                } else {
                    alert(data.msg || '预约失败');
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        }
    }


    // 加载预约记录
    async function loadReservations() {
        const response = await fetch('/user/reservation/list', { method: 'GET' });
        const data = await response.json();

        if (data.code === 1) {
            const tableBody = document.getElementById('reservation-results');
            tableBody.innerHTML = '';
            data.data.forEach(res => {
                const row = document.createElement('tr');
                row.innerHTML = `
                <td>${res.bookTitle}</td>
                <td>${res.reserveTime}</td>
                <td><button class="btn btn-danger" onclick="cancelReservation(${res.id})">取消</button></td>
            `;
                tableBody.appendChild(row);
            });
        }
    }

    // 加载借阅记录
    async function loadBorrowedBooks() {
        try {
            const response = await fetch('/user/borrow/list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();


            if (data.code === 1) {
                const tableBody = document.querySelector('#borrowed tbody');
                tableBody.innerHTML = '';

                data.data.forEach(record => {
                    if (record.status !== 1) return;

                    const row = document.createElement('tr');
                    row.innerHTML = `
                    <td>${record.title}</td>
                    <td>${record.borrowingTime}</td>
                    <td>${record.returnTime}</td>
                    <td>
                        <button class="btn btn-primary" onclick="renewBook('${record.bookId}')">续借</button>
                        <button class="btn btn-secondary" onclick="returnBook('${record.bookId}')">归还</button>
                    </td>
                `;
                    tableBody.appendChild(row);
                });
            } else {
                alert(data.msg || "获取借阅记录失败");
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }

    async function cancelReservation(reservationId) {
        if (!confirm("确定要取消该预约吗？")) return;

        const response = await fetch(`/user/reservation/${reservationId}`, {
            method: 'DELETE'
        });

        const data = await response.json();
        if (data.code === 1) {
            alert("取消成功");
            loadReservations(); // 刷新预约列表
        } else {
            alert(data.msg || "取消失败");
        }
    }


    // 续借图书
    async function renewBook(bookId) {
        if (confirm('确定要续借这本书吗？')) {
            try {
                const response = await fetch('/user/borrow/renew?bookId=' + bookId, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const data = await response.json();
                if (data.code === 1) {
                    alert('续借成功！');
                    loadBorrowedBooks(); // 刷新借阅列表
                } else {
                    alert(data.msg || '续借失败');
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        }
    }


    // 归还图书
    async function returnBook(bookId) {
        if (confirm('确定要归还这本书吗？')) {
            try {
                const response = await fetch('/user/borrow?bookId=' + bookId, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const data = await response.json();
                if (data.code === 1) {
                    alert('归还成功！');
                    loadBorrowedBooks(); // 刷新借阅列表
                    searchBooks(1); // 刷新搜索结果
                } else {
                    alert(data.msg || '归还失败');
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        }
    }

    // 全局变量：存储用户信息
    let user = null;
    // 获取用户信息
    // 页面加载时更新罚款金额
    async function getUserInfo() {
        try {
            const response = await fetch('/user/information', { method: 'GET' });
            const data = await response.json();
            if (data.code === 1 && data.data) {
                user = data.data; // 存储用户信息
                document.getElementById('welcomeMsg').textContent = `欢迎回来，${user.username}`;
                document.getElementById('currentUsername').textContent = user.username;
                document.getElementById('username').textContent = user.username;
                document.getElementById('realName').textContent = user.realName;
                document.getElementById('phone').textContent = user.phone;
                document.getElementById('registerTime').textContent = user.registerTime;
                document.getElementById('fineAmount').textContent = user.fineAmount || '0'; // ✅ 显示罚款金额
            } else {
                document.getElementById('welcomeMsg').textContent = '欢迎回来，访客';
                document.getElementById('currentUsername').textContent = '未登录';
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }



    // 打开修改信息模态框
    function openEditInfoModal() {
        const username = document.getElementById('username').textContent;
        const realName = document.getElementById('realName').textContent;
        const phone = document.getElementById('phone').textContent;

        document.getElementById('editUsername').value = username;
        document.getElementById('editRealName').value = realName;
        document.getElementById('editPhone').value = phone;

        document.getElementById('editInfoModal').style.display = "block";
    }

    // 关闭修改信息模态框
    function closeEditInfoModal() {
        document.getElementById('editInfoModal').style.display = "none";
    }

    // 保存修改信息
    async function saveEditInfo() {
        const oldUsername = document.getElementById('username').textContent;
        const newUsername = document.getElementById('editUsername').value;
        const realName = document.getElementById('editRealName').value;
        const phone = document.getElementById('editPhone').value;

        if (!newUsername || !realName || !phone) {
            alert("请填写所有字段");
            return;
        }

        try {
            const response = await fetch('/user', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldUsername,
                    newUsername,
                    realName,
                    phone
                })
            });

            const data = await response.json();
            if (data.code === 1) {
                alert("信息修改成功");
                closeEditInfoModal();
                getUserInfo(); // 刷新用户信息
            } else {
                alert(data.msg || "修改失败");
            }
        } catch (error) {
            console.error(error);
            alert("网络错误");
        }
    }



    // 打开修改密码模态框
    function openChangePasswordModal() {
        document.getElementById('changePasswordModal').style.display = "block";
    }

    // 关闭修改密码模态框
    function closeChangePasswordModal() {
        document.getElementById('changePasswordModal').style.display = "none";
    }

    // 保存修改密码
    // 修改 saveChangePassword 函数
    async function saveChangePassword() {
        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (!oldPassword || !newPassword || !confirmPassword) {
            alert("请填写所有字段");
            return;
        }

        if (newPassword !== confirmPassword) {
            alert("两次输入的密码不一致，请重新输入");
            return;
        }

        const username = document.getElementById('currentUsername').textContent; // ✅ 改用 currentUsername

        try {
            const response = await fetch('/user/password', { // ✅ 使用 /password 接口
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    oldPassword,
                    newPassword
                })
            });

            const data = await response.json();
            if (data.code === 1) {
                alert("密码修改成功");
                closeChangePasswordModal();
            } else {
                alert(data.msg || "修改失败");
            }
        } catch (error) {
            console.error(error);
            alert("网络错误");
        }
    }



    // 页面加载时初始化数据
    window.onload = function() {
        getUserInfo();
        loadBorrowedBooks();
        searchBooks(1);
        loadReservations();
    };

    function goToPage() {
        const page = parseInt(document.getElementById('go-to-page').value);
        if (!isNaN(page)) {
            searchBooks(page);
        }
    }
</script>
</body>

</html>